<?php

namespace App\Http\Controllers\Util;

use App\Model\Attachment;
use App\Server\UploadServer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UploadController extends Controller
{
    //文件上传
    public function upload(Request $request, UploadServer $uploadServer ,Attachment $attachment){
//      dd($request->file('file'));
        $file=$request->file('file');
        if($file){
            $path=  $uploadServer->upload($file,$this->isImage($file)?'image':'file');
        }
        //存储到数据表
        auth()->user()->attachment()->create(['path'=>url($path)]);
        return ['file'=>url($path),'code'=>0];


    }
    //判断是否是否是图片
    public function isImage($file){
        $ext= strtolower($file->getClientOriginalExtension());
        return in_array($ext,['jpg','png','gif']);
    }

    //文件展示，已经上传图片展示
    public function lists(){
        $data=Attachment::where('user_id',auth()->user()->id)->paginate(2);
        $dat=$data->toArray()['data'];
        foreach ($dat as$k=>$v){
            $dat[$k]['url']=$v['path'];
        }
        return [
            'code'=>0,
            'data'=>$dat,
            'page'=>$data->links().''
        ];
    }
}
